package net.bingosoft.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;

/**
 * @author Zhijie Chen (zigzag.chen@gmail.com)
 */
public class Pipe {

	private InputStream in;

	private OutputStream out;

	private byte[] buf;

	public Pipe() {
		this(null, null, 1024);
	}

	public Pipe(InputStream in, OutputStream out) {
		this(in, out, 1024);
	}

	public Pipe(InputStream in, OutputStream out, int bsize) {
		this.in = in;
		this.out = out;
		if (bsize < 1)
			throw new IllegalArgumentException(
					"bsize must be greater 0 but is " + bsize);
		this.buf = new byte[bsize];
	}

	public InputStream getIn() {
		return this.in;
	}

	public OutputStream getOut() {
		return this.out;
	}

	public void setIn(InputStream in) {
		this.in = in;
	}

	public void setOut(OutputStream out) {
		this.out = out;
	}

	public void dump() {

		if (in != null) {

			while (true) {
				int found;
				// READING
				try {
					found = in.read(buf, 0, buf.length);
				} catch (InterruptedIOException e) {
					break; // out of while
				} catch (IOException e) {
					e.printStackTrace();
					break;
				}
				if (found == -1)
					break;

				if (out == null)
					continue;

				// WRITING
				try {
					out.write(buf, 0, found);
				} catch (InterruptedIOException e) {
					// see comment above
					break;
				} catch (IOException e) {
					e.printStackTrace();
					break;
				}
			}
		}
	}
	
	public void close(){
		if(this.in != null){
			try {
				this.in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(this.out != null){
			try {
				this.out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
